/**
 * 自定义 TinyMCE 插件管理
 * 统一管理所有自定义按钮和插件的注册
 */

/**
 * 注册 AI 切换按钮
 */
export function registerAiToggleButton(editor, { aiState, emit, closeAiPopover, clearAiAttributes, updateCustomPlaceholder, updateAiMarker, editorId, watch, nextTick }) {
  if (!aiState.value) return;
  
  editor.ui.registry.addToggleButton('aiToggle', {
    text: 'AI',
    tooltip: '切换 AI 行内工具',
    onAction: () => {
      const next = !aiState.value;
      aiState.value = next;
      emit('update:aiEnabled', next);
      
      if (!next) {
        closeAiPopover(editorId);
        clearAiAttributes();
      }
      
      updateCustomPlaceholder(aiState.value);
      nextTick(() => updateAiMarker(editorId));
    },
    onSetup: (api) => {
      api.setActive(!!aiState.value);
      const stop = watch(() => aiState.value, (val) => api.setActive(!!val));
      return () => stop();
    }
  });
}

/**
 * 注册上传图片按钮
 */
export function registerUploadImageButton(editor, { openUploadDialog }) {
  editor.ui.registry.addButton('uploadImage', {
    icon: 'image',
    tooltip: '上传图片',
    onAction: () => {
      openUploadDialog('image');
    }
  });
}

/**
 * 注册上传视频按钮
 */
export function registerUploadVideoButton(editor, { openUploadDialog }) {
  editor.ui.registry.addButton('uploadVideo', {
    icon: 'embed',
    tooltip: '上传视频',
    onAction: () => {
      openUploadDialog('video');
    }
  });
}

/**
 * 注册上传音频按钮
 */
export function registerUploadAudioButton(editor, { openUploadDialog }) {
  editor.ui.registry.addButton('uploadAudio', {
    text: '♪',
    tooltip: '上传音频',
    onAction: () => {
      openUploadDialog('audio');
    }
  });
}

/**
 * 注册自定义代码块按钮（示例）
 */
export function registerCodeBlockButton(editor) {
  editor.ui.registry.addButton('customCodeBlock', {
    icon: 'code-sample',
    tooltip: '插入代码块',
    onAction: () => {
      const code = prompt('请输入代码：');
      if (code) {
        editor.insertContent(`<pre><code>${code}</code></pre>`);
      }
    }
  });
}

/**
 * 注册自定义引用块按钮（示例）
 */
export function registerQuoteButton(editor) {
  editor.ui.registry.addButton('customQuote', {
    icon: 'quote',
    tooltip: '插入引用',
    onAction: () => {
      const selection = editor.selection.getContent({ format: 'text' });
      const content = selection || '在此输入引用内容...';
      editor.insertContent(`<blockquote>${content}</blockquote>`);
    }
  });
}

/**
 * 注册自定义分割线按钮（示例）
 */
export function registerDividerButton(editor) {
  editor.ui.registry.addButton('customDivider', {
    text: '---',
    tooltip: '插入分割线',
    onAction: () => {
      editor.insertContent('<hr />');
    }
  });
}

/**
 * 统一注册所有自定义插件
 * @param {Object} editor - TinyMCE 编辑器实例
 * @param {Object} context - 上下文对象，包含所有需要的函数和状态
 */
export function registerAllCustomPlugins(editor, context) {
  // 注册 AI 相关按钮
  if (context.aiEnabled) {
    registerAiToggleButton(editor, context);
  }
  
  // 注册上传相关按钮
  registerUploadImageButton(editor, context);
  registerUploadVideoButton(editor, context);
  registerUploadAudioButton(editor, context);
  
  // 注册更多自定义插件
  registerCodeBlockButton(editor);
  registerQuoteButton(editor);
  registerDividerButton(editor);
}

/**
 * 插件配置对象（可选）
 * 用于管理插件的启用/禁用状态
 */
export const PLUGIN_CONFIG = {
  aiToggle: {
    name: 'aiToggle',
    displayName: 'AI 助手',
    enabled: true,
    register: registerAiToggleButton
  },
  uploadImage: {
    name: 'uploadImage',
    displayName: '上传图片',
    enabled: true,
    register: registerUploadImageButton
  },
  uploadVideo: {
    name: 'uploadVideo',
    displayName: '上传视频',
    enabled: true,
    register: registerUploadVideoButton
  },
  uploadAudio: {
    name: 'uploadAudio',
    displayName: '上传音频',
    enabled: true,
    register: registerUploadAudioButton
  },
  customCodeBlock: {
    name: 'customCodeBlock',
    displayName: '代码块',
    enabled: true,
    register: registerCodeBlockButton
  },
  customQuote: {
    name: 'customQuote',
    displayName: '引用',
    enabled: true,
    register: registerQuoteButton
  },
  customDivider: {
    name: 'customDivider',
    displayName: '分割线',
    enabled: true,
    register: registerDividerButton
  }
};

/**
 * 根据配置动态注册插件
 * @param {Object} editor - TinyMCE 编辑器实例
 * @param {Object} context - 上下文对象
 * @param {Object} config - 插件配置对象（可选，默认使用 PLUGIN_CONFIG）
 */
export function registerPluginsByConfig(editor, context, config = PLUGIN_CONFIG) {
  Object.values(config).forEach(plugin => {
    if (plugin.enabled) {
      try {
        plugin.register(editor, context);
      } catch (error) {
        console.warn(`注册插件 ${plugin.displayName} 失败:`, error);
      }
    }
  });
}
